package cc.ucanuup.service.base.impl;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import cc.ucanuup.common.support.easyui.EasyuiUtil;
import cc.ucanuup.common.support.easyui.inter.EasyuiQuery;
import cc.ucanuup.service.base.dao.UpResourceJPA;
import cc.ucanuup.service.base.entity.Manager;
import cc.ucanuup.service.base.entity.RelationRoleMenus;
import cc.ucanuup.service.base.entity.UpResource;
import cc.ucanuup.service.base.entity.UpUser;
import cc.ucanuup.service.base.inter.ManagerService;
import cc.ucanuup.service.base.inter.RoleMenuService;
import cc.ucanuup.service.base.inter.UpResourceService;
import cc.ucanuup.utils.StringUtil;


/**
 * Description: TODO[描述该类概要功能介绍]
 *
 * @author guwenbin
 * @date 2018年2月1日
 * @version 1.0
 */
@Service
public class UpResourceServiceImpl implements UpResourceService {

	@Autowired
	private UpResourceJPA  upResourceJPA;
	@Autowired
	private RoleMenuService roleMenuService;
	@Autowired
	private ManagerService managerService;
	@Autowired
	private UpResourceService upResourceService;

	@Override
	public UpResource findOne(String id) {

		return upResourceJPA.findOne(id);
	}

	@Override
	public UpResource save(UpResource res) {

		return upResourceJPA.save(res);
	}

	@Override
	public Page<UpResource> queryResourcesAndSortItById(EasyuiQuery bzPage) throws Exception {

		Pageable pageable= new PageRequest(bzPage.getPageNo(), bzPage.getPageSize());
		Map<String, Object>  map = EasyuiUtil.castQueryParam(bzPage);
		return upResourceJPA.queryResourcesAndSortItByFid(map.get("id")== null || ((String)map.get("id")).trim().equals("") ? "%" :(String)map.get("id"), pageable);
	}

	@Override
	public UpResource updateResourceDeleteStatus(String id) {

		UpResource res = upResourceJPA.findOne(id);
		if(res !=null){
			res.setDeleted(1);
			return upResourceJPA.save(res);
		}
		return null;
	}

	@Override
	public UpResource updateResourceStatus(String id) {

		UpResource res = upResourceJPA.findOne(id);
		if(res !=null){
			if(res.getStatus()==0){
				res.setStatus(1);
			}else{
				res.setStatus(0);
			}
			return upResourceJPA.save(res);
		}
		return null;
	}

	private static Object lock = new Object();
	@Override
	public void updateRoleMenus(String[] ids, String roleId, String userAccount) {

		synchronized (lock) {
			List<RelationRoleMenus> saveList = new ArrayList<RelationRoleMenus>();
			List<RelationRoleMenus> delList = new ArrayList<RelationRoleMenus>();
			List<RelationRoleMenus> furList = roleMenuService.findRelationRoleMenusByRoleId(roleId);
			for(RelationRoleMenus fur : furList){
				for(int i =0;i<ids.length ;i++){
					if(i+1 == ids.length && !StringUtil.isEmpty(ids[i])&&!ids[i].equals(fur.getMenuId())){
						delList.add(fur);
					}else if(!StringUtil.isEmpty(ids[i])&&ids[i].equals(fur.getMenuId())){
						break;
					}
				}
				if(ids==null || ids.length == 1 &&StringUtil.isEmpty(ids[0])){
					delList.add(fur);
				}
			}
			for(String id : ids){
				if(furList!=null && furList.size()>0){
					for(int i = 0 ; i<furList.size();i++){
						if(i+1 == furList.size() && !StringUtil.isEmpty(id)&&!id.equals(furList.get(i).getMenuId())){
							RelationRoleMenus frn = new RelationRoleMenus();
							frn.setMenuId(id);
							frn.setRoleId(roleId);
							saveList.add(frn);
						}else if(!StringUtil.isEmpty(id)&&id.equals(furList.get(i).getMenuId())){
							break;
						}
					}
				}else{
					RelationRoleMenus frn = new RelationRoleMenus();
					frn.setMenuId(id);
					frn.setRoleId(roleId);
					saveList.add(frn);
				}
			}
			roleMenuService.mutilSave(saveList);
			roleMenuService.mutilDelete(delList);
		}

	}

	@Override
	public Page<UpResource> queryResourceByFidAndRoleId(EasyuiQuery bzPage) throws Exception {

		Pageable pageable= new PageRequest(bzPage.getPageNo(), bzPage.getPageSize());
		Map<String, Object>  map = EasyuiUtil.castQueryParam(bzPage);
		Page<UpResource> page = upResourceJPA.queryResourceByFid((String)map.get("fid"),pageable);
		if(page.getContent()!=null && page.getContent().size()>0){
			List<UpResource> resList =findResourceByFidAndRoleId((String)map.get("fid"), (String)map.get("roleId"));
			for(int i=0;i<page.getContent().size();i++){
				page.getContent().get(i).setStatus(0);
				for(UpResource res : resList){
					if(page.getContent().get(i).getId().equals(res.getId())){
						page.getContent().get(i).setStatus(1);
					}
				}
			}
		}
		return page;
	}

	/**
	 * @Description: 通过角色Id和 菜单ID查询资源信息
	 * @author WenBin
	 * @param fid
	 * @param roleId
	 * @return
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@Override
	public List<UpResource> findResourceByFidAndRoleId(String fid, String roleId) {
		return upResourceJPA.findResourceByRoleIdAndFid(fid, roleId);
	}

	/**
	 * @Description:  通过
	 * @author WenBin
	 *
	 * @param userType
	 * @return
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@Override
	public List<UpResource> findResourceBySptype(String userType) {

		if(null != userType){
			if(userType.equals("0")){
				return upResourceJPA.findDefaultResourceWithType("default_sp");
			}
			if(userType.equals("1")){
				return upResourceJPA.findDefaultResourceWithType("default_user");
			}
		}
		return null;
	}

	/**
	 *
	 * @Description: 获取所有的资源的权限信息
	 * @author WenBin
	 *
	 * @param sp
	 * @return
	 * @update [日期YYYY-MM-DD] [更改人姓名][变更描述]
	 */
	@Override
	public Set<String> findResourcePermissionsByUserAccount(UpUser sp) {
		Set<String> permission = new HashSet<String>();
		List<UpResource> muList = null;
		Manager manager = managerService.findOneByUserAccount(sp.getUserAccount());
		if(manager!=null){
			muList=upResourceJPA.findAllActiveResource();
		}else{
			muList=upResourceJPA.findAllActiveResourceByUserAccount(sp.getUserAccount());
		}
		List<UpResource> defaultList = upResourceService.findResourceBySptype(sp.getUserType());
		if(muList== null){
			muList = defaultList;
		}else{
			if(defaultList!=null){
				muList.addAll(defaultList);
			}
		}
		for(UpResource sm : muList){
			permission.add(sm.getResPermission());
		}
		return permission;
	}
}
